package vn.smartoffice.promail.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.Getter;
import lombok.Setter;

import org.apache.commons.lang.StringUtils;
import org.zkoss.bind.BindUtils;
import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.GlobalCommand;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.select.annotation.VariableResolver;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zkplus.spring.DelegatingVariableResolver;
import org.zkoss.zul.ListModelList;

import vn.smartoffice.auth.UserService;
import vn.smartoffice.promail.dto.MailFolderNode;
import vn.smartoffice.promail.entity.MailItem;
import vn.smartoffice.promail.services.MailItemService;

@VariableResolver(DelegatingVariableResolver.class)
public class MailItemCtr {

	@WireVariable private UserService userService;

	@WireVariable private MailItemService mailItemService;

	@Getter @Setter private String keyword;
	@Getter @Setter private ListModelList<MailItem> itemListModel;
	@Getter @Setter private MailItem selectedItem;

	@GlobalCommand
	@NotifyChange("itemListModel")
	public void showMailItemList(@BindingParam("base") MailFolderNode base) {
		List<MailItem> listItems = mailItemService.findByUserFolderId(userService.getCurrentUserId(), base.getId());
		itemListModel = new ListModelList<MailItem>(listItems);
	}

	@Command("search")
	@NotifyChange({ "itemListModel", "selectedItem" })
	public void search() {
		if (keyword != null) {
			List<MailItem> listItems = mailItemService.findByTitle(StringUtils.trimToEmpty(keyword));
			itemListModel = new ListModelList<MailItem>(listItems);
		}
	}

	@Command("isCheck")
	@NotifyChange({ "itemListModel", "selectedItem" })
	public void isCheck(@BindingParam("item") MailItem item) {
		item.setImportant(!item.isImportant());
		mailItemService.update(item);
	}

	@Command("setRead")
	@NotifyChange({ "itemListModel", "selectedItem" })
	public void setRead() {
		if (!selectedItem.isCheckRead()) {
			selectedItem.setCheckRead(true);
			mailItemService.update(selectedItem);
		}
		Map<String, Object> dataArgs = new HashMap<>();
		dataArgs.put("selectedItem", selectedItem);
		BindUtils.postGlobalCommand(null, null, "showMailContent", dataArgs);

	}

}
